package com.action.ui.fragment;


import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.action.childbase.ChildBaseFragment;
import com.action.entity.XyBUserRecvRed;
import com.action.service.pressenter.MemberPressenter;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.View.xrecyclerview.RecyclerAdapter;
import com.base.app_core.View.xrecyclerview.RecyclerViewHolder;
import com.base.app_core.model.MoneyData;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.user.model.UserAccount;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;
import com.xinglai.yun.R;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class XYBREDHistoryRecvFrag extends ChildBaseFragment<MemberPressenter> {
    @Inject
    MoneyData moneyData;
    @Inject
    UserAccount userAccount;
    @BindView(R.id.recv_money)
    TextView recvMoney;
    @BindView(R.id.user_money)
    TextView userMoney;
    @BindView(R.id.container)
    XRecyclerView container;

    @BindView(R.id.bannerContainer)
    FrameLayout adView;

    private RedRecvAdapter redRecvAdapter;

    public XYBREDHistoryRecvFrag() {
    }

    private int pageNo = 1;

    @Override
    protected void loadData() {
        super.loadData();
        if (mPresenter != null) {
            mPresenter.fetchRecvHistoryRedPackets(pageNo);
        }
    }

    public class RedRecvAdapter extends RecyclerAdapter<XyBUserRecvRed, RedRecvAdapter.ViewHolder> {

        @Override
        protected void fillData(final XyBUserRecvRed item, RedRecvAdapter.ViewHolder holder) {
            if (item.getType() != 2) {
                XYBAUtils.displayImage_noCache(holder.itemView.getContext(), item.getSenderIcon(), holder.userImage);
                holder.recvName.setText(item.getSenderNickname());
            } else {
                XYBAUtils.displayImage_noCache(holder.itemView.getContext(), AppConstants.APPICON, holder.userImage);
                holder.recvName.setText(AppConstants.APPNAME);
            }
            holder.recvTime.setText(item.getRecTime());
            String userPrice = StringUtils.isEmpty(item.getUserPrice()) ? "0" : item.getUserPrice();
//            holder.recvMoney.setText(new BigDecimal(userPrice).
//                    setScale(4, BigDecimal.ROUND_DOWN).toPlainString() + "元");
            holder.recvMoney.setText(item.getStockCount() + "红包股");
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int type = item.getType();
//                    if (type == 2) {
                        ARouter.getInstance().build(AppConstants.ROUTEURI.BASE_AD_VIEW).withString("sn", item.getSn())
                                .withBoolean("fromOpen", false).navigation();
//                    } else {
//                        ARouter.getInstance().build("/redpacket/detail").withString("sn", item.getSn())
//                                .withInt("type", type).withBoolean("fromOpen", false).navigation();
//                    }
                }
            });
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.unit_user_recv_redpacket;
        }

        public class ViewHolder extends RecyclerViewHolder {
            @BindView(R.id.user_image)
            ImageView userImage;
            @BindView(R.id.recv_name)
            TextView recvName;
            @BindView(R.id.recv_time)
            TextView recvTime;
            @BindView(R.id.recv_money)
            TextView recvMoney;

            public ViewHolder(View itemView) {
                super(itemView);
            }

        }
    }

    private void requestGDTBanner() {
        BannerView bv = new BannerView(getActivity(), ADSize.BANNER, "1107815226", "8070337977963314");
        // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
        // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
        bv.setRefresh(30);
        bv.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(com.qq.e.comm.util.AdError error) {
                Log.i(
                        "AD_DEMO",
                        String.format("Banner onNoAD，eCode = %d, eMsg = %s", error.getErrorCode(),
                                error.getErrorMsg()));
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }
        });
        adView.addView(bv);
        bv.loadAD();
    }

    @Override
    protected void initView() {
        super.initView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        container.setLayoutManager(layoutManager);
        redRecvAdapter = new RedRecvAdapter();
        container.setAdapter(redRecvAdapter);
        container.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                if (mPresenter != null) {
                    mPresenter.fetchRecvHistoryRedPackets(pageNo);
                }
                container.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null && !getActivity().isFinishing() && !getActivity().isDestroyed() && container != null)
                            container.refreshComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }

            @Override
            public void onLoadMore() {
                pageNo++;
                if (mPresenter != null) {
                    mPresenter.fetchRecvHistoryRedPackets(pageNo);
                }
                container.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null && !getActivity().isFinishing() && !getActivity().isDestroyed() && container != null)
                            container.loadMoreComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }
        });
        if(userAccount!=null){
            userMoney.setText(userAccount.getAccount());
        }
        requestGDTBanner();
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recv_history_red_packet;
    }

    @Override
    protected boolean isNeedShowLoading() {
        return true;
    }

    @Override
    protected boolean needShowError() {
        return true;
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == XyBUserRecvRed.class) {
                if (redRecvAdapter == null || container == null) {
                    return;
                }
                if (pageNo == 1) {
                    redRecvAdapter.clear();
                }
                redRecvAdapter.addAll((List<XyBUserRecvRed>) object);
                redRecvAdapter.notifyDataSetChanged();
                if (container != null) {
                    container.setLoadingMoreEnabled(paginated.getHasMore());
                }
            }
            setState(AppConstants.STATE_SUCCESS);
        } else if (object == null && paginated.getCount() == 0) {
            setState(AppConstants.STATE_SUCCESS);
        }

        String recvMoney = moneyData.getRecvMoney();
        if (!StringUtils.isEmpty(recvMoney) && this.recvMoney != null) {
            this.recvMoney.setText(new BigDecimal(recvMoney).setScale(4, RoundingMode.DOWN).toPlainString());
        }
    }
}
